package com.fx.ruankao.controller;

import com.fx.ruankao.entity.ExamPaper;
import com.fx.ruankao.service.ExamPaperService;
import com.fx.ruankao.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Min;
import java.util.List;

/**
 * 试卷控制器 - 管理端
 */
@Validated
@RestController
@RequestMapping("/api/admin/papers")
public class ExamPaperController {
    
    @Autowired
    private ExamPaperService examPaperService;
    
    /**
     * 新增试卷
     */
    @PostMapping
    public Result insert(@RequestBody ExamPaper examPaper) {
        try {
            if (examPaper == null) {
                return Result.error("试卷信息不能为空");
            }
            // 基本参数校验
            if (examPaper.getTitle() == null || examPaper.getTitle().trim().isEmpty()) {
                return Result.error("试卷标题不能为空");
            }
            if (examPaper.getExamDuration() == null || examPaper.getExamDuration() <= 0) {
                return Result.error("考试时长必须大于0");
            }
            if (examPaper.getTotalScore() == null || examPaper.getTotalScore() <= 0) {
                return Result.error("总分必须大于0");
            }
            if (examPaper.getPassScore() == null || examPaper.getPassScore() <= 0) {
                return Result.error("及格分数必须大于0");
            }
            if (examPaper.getPassScore() > examPaper.getTotalScore()) {
                return Result.error("及格分数不能大于总分");
            }
            
            int result = examPaperService.insert(examPaper);
            if (result > 0) {
                return Result.success("新增试卷成功");
            } else {
                return Result.error("新增试卷失败");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID删除试卷
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable @Min(1) Integer id) {
        try {
            int result = examPaperService.deleteById(id);
            if (result > 0) {
                return Result.success("删除试卷成功");
            } else {
                return Result.error("删除试卷失败或试卷不存在");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 更新试卷
     */
    @PutMapping
    public Result update(@RequestBody ExamPaper examPaper) {
        try {
            if (examPaper == null) {
                return Result.error("试卷信息不能为空");
            }
            if (examPaper.getId() == null || examPaper.getId() <= 0) {
                return Result.error("试卷ID不能为空且必须大于0");
            }
            // 基本参数校验
            if (examPaper.getTitle() == null || examPaper.getTitle().trim().isEmpty()) {
                return Result.error("试卷标题不能为空");
            }
            
            int result = examPaperService.update(examPaper);
            if (result > 0) {
                return Result.success("更新试卷成功");
            } else {
                return Result.error("更新试卷失败或试卷不存在");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询试卷
     */
    @GetMapping("/{id}")
    public Result selectById(@PathVariable @Min(1) Integer id) {
        try {
            ExamPaper examPaper = examPaperService.selectById(id);
            if (examPaper != null) {
                return Result.success(examPaper);
            } else {
                return Result.error("未找到试卷");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 查询所有试卷
     */
    @GetMapping
    public Result selectAll() {
        try {
            List<ExamPaper> examPapers = examPaperService.selectAll();
            return Result.success(examPapers);
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 批量删除试卷
     */
    @DeleteMapping("/batch")
    public Result batchDelete(@RequestBody Integer[] ids) {
        try {
            if (ids == null || ids.length == 0) {
                return Result.error("请至少选择一个要删除的试卷");
            }
            
            int result = examPaperService.batchDelete(ids);
            if (result > 0) {
                return Result.success("批量删除试卷成功");
            } else {
                return Result.error("批量删除试卷失败");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据试卷名称查询试卷
     */
    @GetMapping("/title/{title}")
    public Result selectByTitle(@PathVariable String title) {
        try {
            if (title == null || title.trim().isEmpty()) {
                return Result.error("试卷标题不能为空");
            }
            
            List<ExamPaper> examPapers = examPaperService.selectByTitle(title);
            return Result.success(examPapers);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据科目查询试卷
     */
    @GetMapping("/subject/{subject}")
    public Result selectBySubject(@PathVariable String subject) {
        try {
            if (subject == null || subject.trim().isEmpty()) {
                return Result.error("科目不能为空");
            }
            
            List<ExamPaper> examPapers = examPaperService.selectBySubject(subject);
            return Result.success(examPapers);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据状态查询试卷
     */
    @GetMapping("/status/{status}")
    public Result selectByStatus(@PathVariable Integer status) {
        try {
            if (status == null || (status != 0 && status != 1 && status != 2)) {
                return Result.error("状态值无效，只能为0(未发布)、1(已发布)、2(已结束)");
            }
            
            List<ExamPaper> examPapers = examPaperService.selectByStatus(status);
            return Result.success(examPapers);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 更新试卷状态
     */
    @PutMapping("/{id}/status/{status}")
    public Result updateStatus(@PathVariable @Min(1) Integer id, @PathVariable Integer status) {
        try {
            if (status == null || (status != 0 && status != 1 && status != 2)) {
                return Result.error("状态值无效，只能为0(未发布)、1(已发布)、2(已结束)");
            }
            
            boolean result = examPaperService.updateStatus(id, status);
            if (result) {
                return Result.success("更新试卷状态成功");
            } else {
                return Result.error("更新试卷状态失败或试卷不存在");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    

}